package com.lsyw.intergrate.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.entity.SysMenu;
import com.lsyw.intergrate.entity.SysRole;
import com.lsyw.intergrate.entity.SysRoleMenu;
import com.lsyw.intergrate.entity.SysUsersRoles;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.lsyw.intergrate.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2023-04-21
 */
@Api(tags = "角色表")
@RestController
@RequestMapping("/sys-role")
public class SysRoleController {

    @Autowired
    private SysUsersRolesService sysUsersRolesService;


    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 设置权限
     */
    @GetMapping("/set-menu-by-id")
    @ApiOperation(value = "设置权限", notes = "设置权限", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "menuIds", value = "权限点id ,号分隔", required = true, paramType = "query", dataType = "String")
    })
    public Result setMenu(String id, String menuIds) {
        LambdaQueryWrapper<SysRoleMenu> lambda = new QueryWrapper<SysRoleMenu>().lambda();
        lambda.eq(SysRoleMenu::getDelFlag, 0);
        lambda.eq(SysRoleMenu::getRoleId, id);
        List<SysRoleMenu> list = this.sysRoleMenuService.list(lambda);
        for (SysRoleMenu s : list) {
            s.setDelFlag(1);
            this.sysRoleMenuService.updateById(s);
        }

        if (!StringUtils.isEmpty(menuIds)) {
            String[] split = menuIds.split(",");
            int n = 0;
            for (String menuId : split) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setId(IdUtil.simpleUUID());
                sysRoleMenu.setRoleId(id);
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenu.setSort(n);
                sysRoleMenu.setStatus(1);
                sysRoleMenu.setDelFlag(0);
                this.sysRoleMenuService.save(sysRoleMenu);
                n++;
            }
        }
        return Result.successResult(null);
    }

    /**
     * 通过id查询
     */
    @GetMapping("/get-by-id")
    public Result getById(String id) {
        return Result.successResult(sysRoleService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增角色", notes = "新增角色", httpMethod = "POST")
    public Result save(@RequestBody SysRole sysRole) {
        sysRole.setId(IdUtil.simpleUUID());
        sysRole.setDelFlag(0);
        SysRole role = new SysRole();
        role.setName(sysRole.getName());
        role.setRemark(sysRole.getRemark());
        role.setId(IdUtil.simpleUUID());
        role.setGmtCreate(new Date());
        role.setDelFlag(0);
        sysRoleService.save(role);

        return Result.successResult(null);
    }

    /**
     * 通过id删除
     */
    @GetMapping("/delete-by-id")
    @ApiOperation(value = "通过id删除", notes = "通过id删除", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    public Result delete(String id) {
        SysRole role = sysRoleService.getById(id);
        role.setDelFlag(1);
        this.sysRoleService.updateById(role);
        return Result.successResult(null);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改", notes = "修改", httpMethod = "POST")
    public Result updateById(@RequestBody SysRole sysRole) {
        sysRoleService.updateById(sysRole);
        return Result.successResult(null);
    }


    /**
     * 初始化权限点
     */
    @GetMapping("/csh")
    @ApiOperation(value = "初始化权限点", notes = "初始化权限点", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "用户id", required = true, paramType = "query", dataType = "String")
    })
    public Result getMenu(String roleId) {
        List<SysMenu> sysMenuLis = new ArrayList<>();
        LambdaQueryWrapper<SysRoleMenu> lambda = new QueryWrapper<SysRoleMenu>().lambda();
        lambda.eq(SysRoleMenu::getDelFlag, 0);
        lambda.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> list = this.sysRoleMenuService.list(lambda);
        for (SysRoleMenu sysRoleMenu : list) {
            SysMenu sysMenu = this.sysMenuService.getById(sysRoleMenu.getMenuId());
            sysMenuLis.add(sysMenu);
        }
        return Result.successResult(sysMenuLis);
    }

    /**
     * 查询列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取所有角色", notes = "获取所有角色", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, paramType = "query", dataType = "String")
    })
    public Result list(String userId) {
        Map<String ,Object> map = new HashMap<>();
        LambdaQueryWrapper<SysRole> lambda = new QueryWrapper<SysRole>().lambda();
        lambda.eq(SysRole::getDelFlag, 0);
        map.put("all",sysRoleService.list(lambda));

        LambdaQueryWrapper<SysUsersRoles> lambdaQueryWrapper = new QueryWrapper<SysUsersRoles>().lambda();
        lambdaQueryWrapper.eq(SysUsersRoles::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysUsersRoles::getUserId, userId);
        List<SysUsersRoles> list = this.sysUsersRolesService.list(lambdaQueryWrapper);
        List<String> selected = new ArrayList<>() ;
        for (SysUsersRoles sysUsersRoles: list){
            String roleId = sysUsersRoles.getRoleId();
            selected.add(roleId);
        }
        map.put("selected",selected);
        return Result.successResult(map);
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "condition:name", value = "名称", required = false, paramType = "query", dataType = "String")
    })
    public Result page(@RequestBody PageInfo pageInfo) {
        Page<SysRole> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        LambdaQueryWrapper<SysRole> lambda = new QueryWrapper<SysRole>().lambda();
        if (!StringUtils.isEmpty(pageInfo.getCondition().get("name"))) {
            lambda.like(SysRole::getName, pageInfo.getCondition().get("name").toString());
        }
        lambda.eq(SysRole::getDelFlag, 0);
        return Result.successResult(this.sysRoleService.page(page, lambda));
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<SysRole> lambda, SysRoleReqVo param) {
        if (!StringUtils.isEmpty(param.getId())) {
            lambda.eq(SysRole::getId, param.getId());
        }
        if (!StringUtils.isEmpty(param.getName())) {
            lambda.eq(SysRole::getName, param.getName());
        }
        if (!StringUtils.isEmpty(param.getRemark())) {
            lambda.eq(SysRole::getRemark, param.getRemark());
        }
        if (!StringUtils.isEmpty(param.getDataScope())) {
            lambda.eq(SysRole::getDataScope, param.getDataScope());
        }
        if (!StringUtils.isEmpty(param.getLevel())) {
            lambda.eq(SysRole::getLevel, param.getLevel());
        }
        if (!CollectionUtils.isEmpty(param.getCreateTimeList())) {
            lambda.ge(SysRole::getCreateTime, param.getCreateTimeList().get(0));
            lambda.le(SysRole::getCreateTime, param.getCreateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getPermission())) {
            lambda.eq(SysRole::getPermission, param.getPermission());
        }
        if (!CollectionUtils.isEmpty(param.getUpdateTimeList())) {
            lambda.ge(SysRole::getUpdateTime, param.getUpdateTimeList().get(0));
            lambda.le(SysRole::getUpdateTime, param.getUpdateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getIsDel())) {
            lambda.eq(SysRole::getIsDel, param.getIsDel());
        }
        lambda.orderBy(true, false, SysRole::getId);
    }


    /**
     * 请求model
     */
    @Data
    @AllArgsConstructor
    private static class SysRoleReqVo extends SysRole {
        private List<String> createTimeList; // 创建日期起止
        private List<String> updateTimeList; // 起止
    }


}
